#! /bin/bash

set -e

IMAGE_NAME="bbb.img"
IMAGE_SIZE_MB=3000

pr_info () {
    echo -e "\033[0;32m$*\033[0m"
}

cd_bbb () {
    if [ -z $BBB_WS ]; then
        echo "No env: BBB_WS"
        exit
    fi
    cd $BBB_WS
}


#cd_bbb
#
#rm -rf image
#mkdir image

cd $1

rm -f $IMAGE_NAME

pr_info "[image] dd"
dd if=/dev/zero of=$IMAGE_NAME bs=1M count=$IMAGE_SIZE_MB

pr_info "[image] fdisk"
cat << EOF | fdisk $IMAGE_NAME
n
p
1

+128M
n
p
2


t
1
c
a
1
w
EOF

LOOPDEV=$(losetup -f)

pr_info "[image] losetup attach: $LOOPDEV $IMAGE_NAME"
losetup $LOOPDEV $IMAGE_NAME

pr_info "[image] kpartx add"
kpartx -av $LOOPDEV


PART_BOOT="/dev/mapper/${LOOPDEV/\/dev\/}p1"
PART_ROOTFS="/dev/mapper/${LOOPDEV/\/dev\/}p2"

pr_info "[image] mkfs vfat"
mkfs.vfat -F 32 -n "boot" $PART_BOOT

pr_info "[image] mkfs ext4"
mkfs.ext4 -L "rootfs" $PART_ROOTFS

rm -rf mnt_boot
rm -rf mnt_rootfs

mkdir mnt_boot
mkdir mnt_rootfs

mount $PART_BOOT mnt_boot
mount $PART_ROOTFS mnt_rootfs

df -hT

cp -v boot/* mnt_boot/
#cp -v rootfs/* mnt_rootfs

df

sync

umount mnt_boot
umount mnt_rootfs

rm -rf mnt_boot
rm -rf mnt_rootfs

pr_info "[image] kpartx del"
kpartx -dv $LOOPDEV

pr_info "[image] losetup detach"
losetup -d $LOOPDEV
